package com.sjs.flow.service.impl;

import com.sjs.flow.entity.vo.ProcessDefinitionVo;
import com.sjs.flow.http.exception.PlatformException;
import com.sjs.flow.service.BpmnModelService;
import org.apache.commons.text.StringEscapeUtils;
import org.flowable.bpmn.converter.BpmnXMLConverter;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.common.engine.api.FlowableException;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.ProcessDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author uto_dev_008
 * @desc
 * @since 2022/7/27 10:39
 * Copyright (c) 2021 南京友拓信息技术有限公司 All rights reserved
 */
@Service
public class BpmnModelServiceImpl implements BpmnModelService {

    @Autowired
    RepositoryService repositoryService;

    /**
     * 保存流程定义
     *
     * @param processDefinitionVo
     * @return
     */
    @Override
    public Deployment generateProcess(ProcessDefinitionVo processDefinitionVo) {
        String bpmnStr = processDefinitionVo.getBpmnStr();
        byte[] bpmn = Base64.getDecoder().decode(bpmnStr);
        bpmnStr = StringEscapeUtils.unescapeXml(new String(bpmn, StandardCharsets.UTF_8));
        String fileName = "sjs-" + processDefinitionVo.getProcessKey() + "-bpmn20.xml";
        Deployment deployment = null;
        try {
            deployment = repositoryService.createDeployment()
                    .addInputStream(fileName, new ByteArrayInputStream(bpmnStr.getBytes(StandardCharsets.UTF_8))).name(fileName).deploy();
        } catch (FlowableException e) {
            throw new PlatformException("流程配置不合法", 10301024, e);
        }
        return deployment;
    }

    /**
     * 获取流程定义
     *
     * @param processKey
     * @return
     */
    @Override
    public String getDefinition(String processKey) throws UnsupportedEncodingException {
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionKey(processKey).latestVersion().singleResult();
        String base64Xml = "";
        if (processDefinition != null) {
            BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
            //创建转换对象
            BpmnXMLConverter converter = new BpmnXMLConverter();
            //把bpmnModel对象转换成字符
            byte[] bytes = converter.convertToXML(bpmnModel);
            String xmlContenxt = new String(bytes, StandardCharsets.UTF_8);
            base64Xml = Base64.getEncoder().encodeToString(xmlContenxt.getBytes("UTF-8"));
        }
        return base64Xml;
    }
}
